<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

 class MY_Log extends CI_Log{
 	
 	public function __construct(){
 		parent::__construct();
 	}
 	
 	function w( $level = 'error',$output, $php_error = false, $username = false, $callSource = false, $input = false){
		//username
		if($username === false){
			$username = 'not-give-username';
			if(isset($_SESSION['username'])){
				$username = $_SESSION['username'];
			}
		}
		//分隔符
		$separator = ' | ';
		//sessionid
		$sesionId = session_id();
		//ip
		$ip = $_SERVER['REMOTE_ADDR'];
		//调用源
		if($callSource === false){
			global $class,$method;;
			$callSource = $class.'->'.$method;
		}
		/*if($input === false){
			if(isset($this->params)){
				if(isset($this->params['url']) && count($this->params['url']) > 1){
					$gets = array();
					foreach($this->params['url'] as $k => $v){
						if($k != 'url'){
							$gets[$k] = $v;
						}
					}
					$input .= 'GET'.json_encode($gets);
				}
				if(isset($this->params['form']) && count($this->params['form']) > 0){
					$input .= 'POST'.json_encode($this->params['form']);
				}
			}
		}*/
		if($input === false){
			$input = 'no-input';
		}
		if(!is_string($input)){
			$input = json_encode($input);
		}
		if(strlen($input) > 150){
			$input = substr($input, 0, 150).'...';
		}
		//输出
		if(!is_string($output)){
			$output = json_encode($output);
		}
		if(strlen($output) > 8500){
			$output = substr($output, 0, 8500).'...';
		}
		
		$message = array( $level, $username, $sesionId, $ip, $callSource, $input, $output);
		$message = $separator.join($separator, $message);
		
		
	//	print_r($action);
	//	$s = $action['params']['controller']
	//	$t = debug_backtrace();
	//	print_r($t);
	
		return $this->w_log('site',$level, $message, $php_error);
	}
	
	/**
	 * 取给定时间与当前时间的时间差，毫秒
	 */
	function lt($sTime, $now = false){
		if(!$now) $now = explode(' ', microtime());
		return number_format((($now[1] - $sTime[1]) + ($now[0] - $sTime[0]))  * 1000, 3);
	}
	
 	public function w_log($logName, $level = 'error', $msg, $php_error = FALSE)
	{
		if ($this->_enabled === FALSE)
		{
			return FALSE;
		}

		$level = strtoupper($level);

		if ( ! isset($this->_levels[$level]) OR ($this->_levels[$level] > $this->_threshold))
		{
			return FALSE;
		}

		$filepath = $this->_log_path.'log-'.$logName.'-'.date('Y-m-d').'.php';
		$message  = '';

		if ( ! file_exists($filepath))
		{
			$message .= "<"."?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?".">\n\n";
		}

		if ( ! $fp = @fopen($filepath, FOPEN_WRITE_CREATE))
		{
			return FALSE;
		}

		$message .= $level.' '.(($level == 'INFO') ? ' -' : '-').' '.date($this->_date_fmt). ' --> '.$msg."\n";

		flock($fp, LOCK_EX);
		fwrite($fp, $message);
		flock($fp, LOCK_UN);
		fclose($fp);

		@chmod($filepath, FILE_WRITE_MODE);
		return TRUE;
	}
	
 }